home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 26 / Cream of the Crop 26.iso / program / ddj0897.zip / RCSC.ZIP / DEMO86 / MCHOPSTK.C < prev    next >
C/C++ Source or Header  |  1997-01-12  |  1KB  |  43 lines

  1. #include <stdio.h>
  2.  
  3. /* data for the chopstick monitor */
  4. static int chopsticks[] = {2, 2, 2, 2, 2};    /* chopstick counts */
  5. static int myright[] = {1, 2, 3, 4, 0};        /* right neighbor identity */
  6. static int myleft[] = {4, 0, 1, 2, 3};        /* left neighbor identity */
  7. static CONDITION waiting[5];            /* condition variables */
  8.  
  9. /* initialization for chopstick monitor */
  10. void monitor mchopstk()
  11. {
  12.     /* demonstrates that this is being called during initialization */
  13.     printf("Initializing chopsticks monitor...\n");
  14. }
  15.  
  16. /* monitor entry to get both chopsticks */
  17. void entry GetChopsticks(id)
  18. int id;
  19. {
  20.     /* wait until both chopsticks available */
  21.     if (chopsticks[id] != 2)
  22.         Wait(&waiting[id]);
  23.  
  24.     /* decrement neighbors' chopstick counts */
  25.     chopsticks[myright[id]]--;
  26.     chopsticks[myleft[id]]--;
  27. }
  28.  
  29. /* monitor entry to release the 2 chopsticks */
  30. void entry PutChopsticks(id)
  31. int id;
  32. {
  33.     /* increment neighbors' chopstick counts and wake 
  34.         them up if they now have both chopsticks */
  35.     if (++chopsticks[myright[id]] == 2)
  36.         Signal(&waiting[myright[id]]);
  37.         
  38.     if (++chopsticks[myleft[id]] == 2)
  39.         Signal(&waiting[myleft[id]]);
  40.         
  41. }
  42.  
  43.